<template>
  <el-dialog
    v-model="dialogVisible"
    width="260"
    draggable
    :modal="false"
    :close-on-click-modal="false"
    :show-close="false"
    :fullscreen="false"
  >
    <template #header>
      <div class="flex justify-between text-inherit">
        <div>请登录话机</div>
        <div class="cursor-pointer text-#337ecc">
          <span @click="close"
            ><el-icon><CloseBold /></el-icon
          ></span>
        </div>
      </div>
    </template>
    <div class="call-b">
      <span class="labels">请选择:</span>
      <el-radio-group v-model="phoneMode" @change="setPhoneMode">
        <el-radio label="sip">SIP话机</el-radio>
        <el-radio label="recall">双向回拨</el-radio>
        <el-radio label="box">话机盒子</el-radio>
        <el-radio label="sim">手机SIM卡</el-radio>
      </el-radio-group>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { CloseBold } from '@element-plus/icons-vue'
import { usePhoneStore } from '@/store/modules/phone'
import WebPhone from '@/hooks/web/useCall'

const useStore = usePhoneStore()

const phoneModeMap = {
  sip: 'SIP话机',
  recall: '双向回拨',
  box: '话机盒子',
  sim: '手机SIM卡'
}
const dialogVisible = ref(false)
const phoneMode = ref(null)

/*打开*/
const open = async () => {
  if (!dialogVisible.value) {
    phoneMode.value = useStore.getPhoneMode
    dialogVisible.value = true
  }
}
/*关闭*/
const close = () => {
  useStore.setIsDialog(false)
  dialogVisible.value = false
}
const audioConstraints = {
  video: false,
  audio: {
    noiseSuppression: true,
    echoCancellation: true
  },
  logicalSurface: false
}

/*选择模式*/
const setPhoneMode = async (pm) => {
  try {
    if (pm == 'sip') {
      await navigator.mediaDevices.getUserMedia(audioConstraints)
    }
  } catch {
    phoneMode.value = null
    ElMessage.warning('未识别到麦克风,请检查麦克风')
    return
  }
  await useStore.setPhoneMode(pm)
  phoneMode.value = pm
  WebPhone.getInstance().reg()
  setTimeout(() => {
    close()
  }, 1e3)
}

defineOptions({ name: 'CallTask' })

defineExpose({ open, close })
</script>

<style scoped lang="scss">
.call-b {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  align-items: flex-start;
  .labels {
    width: 100%;
    padding-top: 8px;
  }
}
.el-radio {
  width: 90px;
  margin-right: 20px;
}
</style>
